package com.group.service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.group.dao.BookDao;
import com.group.dao.GeneralBeanDao;
import com.group.dao.NewsDao;
import com.group.model.*;
import com.group.util.WeiXinConf;
import com.group.util.WeiXinUtils;

@Service
public class BookScheduleService {
	private static final Logger logger = LoggerFactory.getLogger(BookScheduleService.class);

	@Autowired
	GeneralBeanDao beanDao;

	@Autowired
	BookDao bookDao;

	@Autowired
	TickerService tickerService;

	Random r = new Random();

	SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

	/**
	 * 每日领币
	 */
	//@Scheduled(cron = "0 10 1 * * ?")
	public void handleGetTokenEveryday() {
		// 查询昨日消费的书币
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_YEAR, -1);

		String date = df.format(cal.getTime());

		double totalCost = bookDao.countCost(date);

		List<ReadLogView> views = bookDao.queryReadLogView(date);

		// 给每个人增加币
		for (ReadLogView view : views) {
			if (view.getUserId() == null)
				continue;

			double amount = view.getTotalCost() * 10000 / totalCost;

			UserTickerLog log = tickerService.addTicker(view.getUserId(), "wecc", new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(), "看书领币");
			log.setCost(view.getTotalCost());
			beanDao.save(log);
		}

	}

	/**
	 * 计算小说的统计信息,总资产 ,收益率 等
	 */
	//@Scheduled(cron = "0 10 2 * * ?")
/*	public void handleBookStatistic() {
		Calendar cal = Calendar.getInstance();
		Calendar calday = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		calday.set(Calendar.HOUR_OF_DAY, 0);
		calday.set(Calendar.MINUTE, 0);
		calday.set(Calendar.SECOND, 0);
		cal.add(Calendar.DAY_OF_YEAR, -1);
		calday.add(Calendar.DAY_OF_YEAR,0);
		Date yesterday = cal.getTime();
		Date today = calday.getTime();
		List<Book> books = beanDao.queryList(new Book());
		//人民币与WECC汇率,用于计算年化收益率
//		String rate = beanDao.quickQueryOne(SystemPara.class, "name", "weccExchangeRate").getValue();
		String rate = "50";

		for (Book book : books) {
			// 年化收益公式 =【(当前书刊昨日消耗总书币*0.005元*80%*人民币与WECC汇率)/昨日该书刊存有的WECC总量】*365
			double totalInvest = bookDao.countBookTotalInvest(book.getId());//该书投资的总额

			book.setCopyrightValue(totalInvest);
			double yesterdayTotalInvest = bookDao.countBookyesterdayTotalInvest(book.getId(),yesterday,today);//该书昨日投资的总额
			if (yesterdayTotalInvest < 100 || yesterdayTotalInvest == 0) {
				yesterdayTotalInvest = 100;
			}
			double profit = 1.0;
			if(book.getYearstate()==0){
//				profit = totalCost * 0.005 * 0.6 * Double.parseDouble(rate) * 365 / totalInvest;
				profit = (yesterdayTotalInvest+totalInvest/50)* 0.005 * Double.parseDouble(rate) * 365 / totalInvest;
			}else{
				profit = book.getProfit();
			}
			book.setProfit(new BigDecimal(profit).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
			beanDao.save(book);

			// 处理用户分红
			List<BookInvestLog> investLogs = bookDao.queryBookInvestLogByBookId(book.getId());
			double totalBonus = 0d;
			for (BookInvestLog log : investLogs) {
				double bonus = log.getAmount() * log.getWeight() * profit / 365;
				totalBonus += bonus;

				tickerService.addTicker(log.getUserId(), "wecc", bonus, "投资分红");

				BookBonusLog blog = new BookBonusLog();
				blog.setUserId(log.getUserId());
				blog.setBookId(log.getBookId());
				blog.setName(log.getName());
				blog.setBonus(bonus);
				blog.setBookInvestLogId(log.getId());
				blog.setInvestAmount(log.getAmount());

				beanDao.save(blog);

				log.setProfit(log.getProfit() + bonus);
				beanDao.save(log);
			}
			book.setBonus(totalBonus);
			beanDao.save(book);

		}

	}*/

	/**
	 * 计算小说的统计信息,总资产 ,收益率 等
	 */
	//@Scheduled(cron = "0 10 2 * * ?")
	public synchronized void handleBookStatistic() {
		// 处理用户分红
		List<BookInvestLog> investLogs = bookDao.queryAllBookInvestLogByBookId();
		Book  bookquery = new Book();
		for (BookInvestLog log : investLogs) {
			bookquery = bookDao.queryBookByBookId(log.getBookId());
			if(bookquery == null){
				continue;
			}
			double bonus = log.getAmount() * log.getWeight() * bookquery.getProfit() / 365;
			tickerService.addTickerCatch(log.getUserId(), "wecc", bonus, "投资分红");
			BookBonusLog blog = new BookBonusLog();
			blog.setUserId(log.getUserId());
			blog.setBookId(log.getBookId());
			blog.setName(log.getName());
			blog.setBonus(bonus);
			blog.setBookInvestLogId(log.getId());
			blog.setInvestAmount(log.getAmount());
			beanDao.save(blog);
			log.setProfit(log.getProfit() + bonus);
			beanDao.save(log);
		}

		List<Book> books = beanDao.queryList(new Book());
		for (Book book : books) {
			double totalInvest = bookDao.countBookTotalInvest(book.getId());//该书投资的总额
			book.setCopyrightValue(totalInvest);
			beanDao.save(book);
		}
	}

	/**
	 * 增加收益到用户的余额中
	 */
	//@Scheduled(cron = "0 10 4 * * ?")
	public synchronized void handleUserTicker() {
		Timestamp d = new Timestamp(System.currentTimeMillis());
		String date = d.toString().substring(0,10);
		List<BookBonusLog> bookBonusLogsList = bookDao.queryAllBookBonusLogByBookId(date);
		List<UserTicker> userTickerList = bookDao.queryUserticker(date);
		for (int x = 0; x<userTickerList.size();x++) {
			if(userTickerList.get(x).getUserId().equals(bookBonusLogsList.get(x).getUserId())){
				userTickerList.get(x).setNum(bookBonusLogsList.get(x).getBonus()+userTickerList.get(x).getNum());
				beanDao.save(userTickerList.get(x));
			}
		}
	}

	/**
	 * 处理到期回款
	 */
	//@Scheduled(cron = "0 10 4 * * ?")
	public void handExpireInvest() {
		List<BookInvestLog> logs = bookDao.queryExpireBookInvestLog();

		for (BookInvestLog log : logs) {
			log.setState(1);
			beanDao.save(log);

			// 投资到期回款
			tickerService.addTicker(log.getUserId(), "wecc", log.getAmount(), "投资到期回款");
		}

	}

}
